package eu.liamkleist.autocompletetest;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import model.Location;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements TextWatcher {

	private final static String TAG = "MainActivity";

	private int i = 0;

	private AutoCompleteTextView autoCompleteTextView;
	private TextView textView;
	private TextView onTextChangedCounter;
	private Button deleteImageView;

	ArrayList<Location> locList;
	ArrayList<String> locListString;

	private String baseUrl;

	final String item[] = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		baseUrl = getString(R.string.baseUrl);

		locList = new ArrayList<Location>();
		locListString = new ArrayList<String>();

		deleteImageView = (Button) findViewById(R.id.deleteImageView);
		deleteImageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				autoCompleteTextView.setText("");

			}
		});

		autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
		autoCompleteTextView.addTextChangedListener(this);

		autoCompleteTextView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO
				try {
					textView.setText(locListString.get(arg2));
					Log.d(TAG, locList.get(arg2).getLocationName());
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), e.getMessage(),
							Toast.LENGTH_LONG).show();
				}

			}
		});
		// autoCompleteTextView.setOnItemClickListener(new OnItemClickListener()
		// {
		//
		// @Override
		// public void onItemClick(AdapterView<?> parentView, View view,
		// int position, long id) {
		// textView.setText(locList.get(position).getLocationName());
		// }
		// });
		onTextChangedCounter = (TextView) findViewById(R.id.onTextChangedCounter);
		textView = (TextView) findViewById(R.id.textView);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void afterTextChanged(Editable s) {

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {

		locListString.clear();
		locList.clear();
		++i;
		onTextChangedCounter.setText("onTextChanged: " + i + " times.");

		final String myUrl = getUrl();
		new LocationAsyncTask().execute(myUrl);

	}

	private String getUrl() {
		String tempUrl = baseUrl + getText(R.string.location_feed)
				+ autoCompleteTextView.getText();
		tempUrl = tempUrl.replaceAll(" ", "%20");
		final String myUrl = tempUrl;
		return myUrl;
	}

	String[] myList2 = null;

	private class LocationAsyncTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... arg0) {

			try {

				URL url = new URL(arg0[0]);

				URLConnection connection;
				connection = url.openConnection();

				HttpURLConnection httpConnection = (HttpURLConnection) connection;
				int responseCode = httpConnection.getResponseCode();

				if (responseCode == HttpURLConnection.HTTP_OK) {
					InputStream in = httpConnection.getInputStream();

					DocumentBuilderFactory dbf = DocumentBuilderFactory
							.newInstance();
					DocumentBuilder db = dbf.newDocumentBuilder();

					// Parse the location feed.
					Document dom = db.parse(in);
					Element docEle = dom.getDocumentElement();

					// Get a city entry.

					NodeList nl = docEle.getElementsByTagName("StopLocation");
					if (nl != null && nl.getLength() > 0) {
						for (int i = 0; i < nl.getLength(); i++) {

							Node node = nl.item(i);

							if (node.hasAttributes()) {
								Location location = new Location();

								Attr attr = (Attr) node.getAttributes()
										.getNamedItem("name");
								if (attr != null) {
									location.setLocationName(attr.getValue());
									locListString.add(attr.getValue());
								}

								attr = (Attr) node.getAttributes()
										.getNamedItem("x");
								if (attr != null) {
									location.setX(Integer.parseInt(attr
											.getValue()));
								}

								attr = (Attr) node.getAttributes()
										.getNamedItem("y");
								if (attr != null) {
									location.setY(Integer.parseInt(attr
											.getValue()));
								}

								attr = (Attr) node.getAttributes()
										.getNamedItem("id");
								if (attr != null) {
									location.setId(Integer.parseInt(attr
											.getValue()));
								}

								attr = (Attr) node.getAttributes()
										.getNamedItem("type");
								if (attr != null) {
									location.setType(attr.getValue());
								}

								locList.add(location);
								// Log.d(TAG, node.getNodeName());

							}
						}
					}

					nl = docEle.getElementsByTagName("CoordLocation");
					if (nl != null && nl.getLength() > 0) {
						for (int i = 0; i < nl.getLength(); i++) {

							Node node = nl.item(i);

							if (node.hasAttributes()) {
								Location location = new Location();
								Attr attr = (Attr) node.getAttributes()
										.getNamedItem("name");

								if (attr != null) {
									location.setLocationName(attr.getValue());
									locListString.add(attr.getValue());
								}

								attr = (Attr) node.getAttributes()
										.getNamedItem("x");
								if (attr != null) {
									location.setX(Integer.parseInt(attr
											.getValue()));
								}

								attr = (Attr) node.getAttributes()
										.getNamedItem("y");
								if (attr != null) {
									location.setY(Integer.parseInt(attr
											.getValue()));
								}

								attr = (Attr) node.getAttributes()
										.getNamedItem("id");
								if (attr != null) {
									location.setId(Integer.parseInt(attr
											.getValue()));
								}
								attr = (Attr) node.getAttributes()
										.getNamedItem("type");
								if (attr != null) {
									location.setType(attr.getValue());
								}

								locList.add(location);

							}
						}
					}

				}
			} catch (MalformedURLException e) {
				Log.d(TAG, "MalformedURLException");
			} catch (IOException e) {
				Log.d(TAG, "IOException");
			} catch (ParserConfigurationException e) {
				Log.d(TAG, "ParserConfigurationException");
			} catch (SAXException e) {
				Log.d(TAG, "SAXException");
			} finally {
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);


			myList2 = locListString.toArray(new String[locListString.size()]);

			ArrayAdapter<String> adapter = new ArrayAdapter<String>(
					getApplicationContext(),
					android.R.layout.simple_dropdown_item_1line, myList2);
			autoCompleteTextView.setAdapter(adapter);
		}
	}
}
